package com.example.yamba;

import java.util.List;

import winterwell.jtwitter.Twitter;
import winterwell.jtwitter.Twitter.Status;
import android.app.Application;
import android.content.ContentValues;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;

public class YambaApplication1 extends Application implements OnSharedPreferenceChangeListener{

	private static final String TAG = YambaApplication1.class.getSimpleName();
	private boolean serviceRunning;
	private StatusData statusData;
	
	
	public Twitter twitter;
	private SharedPreferences prefs;

	
	public StatusData getStatusData()
	{
		if (statusData == null)
			statusData = new StatusData(this);
		
		return statusData;
	}
	
	public synchronized int fetchStatusUpdates()
	{
		Log.d(TAG,"Fetching status updates");
		Twitter twitter = this.getTwitter();
		if (twitter == null)
		{
			Log.d(TAG,"Twitter connection info not initialized");
			return 0;
		}
		
		try
		{
			List<Status> statusUpdates = twitter.getFriendsTimeline();
			Long latestStatusCreaterAtTime = this.getStatusData().getLatestStatusCreatedAtTime();
			int count = 0;
			ContentValues values = new ContentValues();
			for(Status status: statusUpdates){
				values.put(StatusData.C_ID, status.getId());
				long createdAt = status.getCreatedAt().getTime();
				values.put(StatusData.C_CREATED_AT, createdAt);
				values.put(StatusData.C_TEXT, status.getText());
				values.put(StatusData.C_USER, status.user.name);
				
				Log.d(TAG,"Gotupdate with id:" + status.id);
				
				this.getStatusData().insertOrIgnore(values);
				
				if (latestStatusCreaterAtTime < createdAt)
					count++;
			}
			Log.d(TAG,count > 0 ? "Got " + count + "status updates" : "No new status updates");
			
			return count;
		}
		catch(RuntimeException e)
		{
			Log.e(TAG,"FAiled to fetch status updates");
			return 0;
		}
		
	}
	
	
	@Override
	public void onCreate() {
		
		super.onCreate();
		this.prefs = PreferenceManager.getDefaultSharedPreferences(this);
		this.prefs.registerOnSharedPreferenceChangeListener(this);
		Log.i(TAG,"onCreate");
	}



	@Override
	public void onTerminate() {
		super.onTerminate();
		Log.i(TAG,"onTerminate");
	}

	public synchronized Twitter getTwitter()
	{
		if (twitter == null)
		{
			String username, pwd, apRoot;
			username = prefs.getString("username", "");
			pwd = prefs.getString("password", "");
			apRoot = prefs.getString("apiRoot", "");
			
			if (!TextUtils.isEmpty(username) &&
			    !TextUtils.isEmpty(pwd) &&
			    !TextUtils.isEmpty(apRoot))
			{
				twitter = new Twitter(username, pwd);
				twitter.setAPIRootUrl(apRoot);
			}
		}
		
		return this.twitter;
	}

	
	public synchronized void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
			String key) 
	{
		// reset twitter to null so that next time its needed it will get the latest values
		
		twitter = null;
		
	}


	public boolean isServiceRunning()
	{
		return serviceRunning;
	}
	
	public void setServiceRunning(boolean serviceRunning)
	{
		this.serviceRunning = serviceRunning;
	}

	
	
}

